package com.example.tools

import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader

/**
 * 执行命令
 */
object ShellUtils {
    //执行坐标系的点击事件
    fun execYX(X: Int, Y: Int): String {
        return exec("input tap $X $Y -P")
    }

    fun execSwipe(startx: Int, starty: Int, endx: Int, endY: Int) {
        exec("input swipe $startx $starty $endx $endY")
    }


    fun exec(command: String): String {
        var reader: BufferedReader? = null
        var content = ""
        try {
            //("ps -P|grep bg")执行失败，PC端adb shell ps -P|grep bg执行成功
            //Process process = Runtime.getRuntime().exec("ps -P|grep tv");
            //-P 显示程序调度状态，通常是bg或fg，获取失败返回un和er
            // Process process = Runtime.getRuntime().exec("ps -P");
            //打印进程信息，不过滤任何条件
            val process = Runtime.getRuntime().exec(command)
            reader = BufferedReader(InputStreamReader(process.inputStream))
            val output = StringBuffer()
            var read: Int
            val buffer = CharArray(4096)
            while (reader.read(buffer).also { read = it } > 0) {
                output.append(buffer, 0, read)
            }
            reader.close()
            content = output.toString()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return content
    }

}